package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.woniu.entity.ImportSubjectDTO;
import com.woniu.pojo.Subject;
import com.woniu.service.ISubjectService;
import com.woniu.util.Result;
import com.woniu.vo.TreeSubjectVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * <p>
 * 课程科目 前端控制器
 * </p>
 *
 * @author xiaoruan
 * @since 2023-03-14
 */
@Api("课程分类模块")
@RestController
@RequestMapping("/subject")
public class SubjectController extends BaseController{
    @Autowired
    ISubjectService subjectService;

    @ApiOperation("导入subject的excel表")
    @PostMapping("/import")
    public Result importSubject(@RequestPart MultipartFile file) throws IOException {
        //1.使用EasyExcel读取用户上传的内容
        List<ImportSubjectDTO> subjectDTOList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), ImportSubjectDTO.class, new PageReadListener(new Consumer<List>() {
            @Override
            public void accept(List list) {
                subjectDTOList.addAll(list);

            }
        })).sheet().doRead();
        //2.调用service将读取到的数据保存到数据库中
        subjectService.importSubject(subjectDTOList);
        //3.返回数据
        return success();

    }

    @ApiOperation("查询一二级分类")
    @GetMapping("/tree")
    public Result findsubjectTree() {

     List<TreeSubjectVO> treeSubjectVOList = subjectService.findSubjectTrees();



        return toDataResult(treeSubjectVOList);
    }

    @ApiOperation("根据parentID查询分类信息")
    @GetMapping("{parentId}")
    public Result findsubjectByParentId(@PathVariable String parentId) {

        List<Subject> subjectList = subjectService.findsubjectByParentId(parentId);

        return toDataResult(subjectList);
    }


}
